from datetime import datetime, timedelta

from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


# Create your views here.


def set_cookie(request):
    rep = HttpResponse('设置cookie')
    # rep=render()
    # rep=redirect()
    rep.set_cookie(key='age', value='34', expires=2)
    rep.set_cookie('num', 123, expires=(datetime.now() + timedelta(days=1, hours=1, seconds=30)))
    rep.set_signed_cookie('pwd', 'root', salt='pwdsalt')
    return rep


def get_cookie(request):
    age = request.COOKIES.get('age')
    pwd = request.get_signed_cookie('pwd', None, salt='pwdsalt')
    return HttpResponse(f'获取cookie信息num:{age},pwd:{pwd}')


def login_html(request):
    # 从cookie中获取用户名和密码
    username = request.COOKIES.get('username')
    password = request.get_signed_cookie('pwd', None, salt='pwdsalt')
    print(f'request:{request},username:{username},password:{password}')
    if username and password:
        return render(request, 'login.html', {'username': username, 'password': password})
    else:
        return render(request, 'login.html')


def dologin(request):
    # 从登录表单中获取用户名和密码及是否勾选了记住密码
    data = request.POST
    username = data.get('uname')
    password = data.get('pass')
    rember = data.get('rem')
    print(f'request:{request},username:{username},password:{password},rember:{rember}')
    response = HttpResponse()
    if 'root' == username and '123' == password:
        response.content = '登录成功'
        if rember == 'rember':
            # 勾选了记住用户名和密码
            # 将用户名和密码保存到cookie中
            response.set_cookie('username', username, max_age=3 * 24 * 3600)
            response.set_signed_cookie('pwd', password, salt='pwdsalt', max_age=3 * 24 * 3600)
        else:
            # 删除cookie中的之前保存用户名和密码
            response.delete_cookie('username')
            response.delete_cookie('pwd')
        return response
    else:
        response.delete_cookie('username')
        response.delete_cookie('pwd')
        return redirect('cookie_demo_app:login_html')
